Shader "Custom/ToonHair"
{
    Properties
    {
        [MainTexture] _BaseMap("基础颜色贴图", 2D) = "white" {}
        [MainColor] _BaseColor("基础颜色", Color) = (1,1,1,1)
        
        // 头发效果贴图
        _HMMap("头发效果图 (R=高光遮罩, G=AO, B=阴影遮罩)", 2D) = "white" {} // 调整了注释顺序
        
        // MatCap设置
        _MatCapTex("MatCap高光贴图", 2D) = "white" {}
        _MatCapIntensity("MatCap高光强度", Range(0, 5)) = 1.0
        _MatCapColor("MatCap高光颜色", Color) = (1,1,1,1)
        
        // 卡通阴影 Ramp 设置
        _RampTex("阴影渐变贴图", 2D) = "white" {}
        _RampOffset("阴影边界偏移", Range(-1, 1)) = 0.0 // 调整范围
        _RampSmooth("阴影边界平滑度", Range(0.001, 1.0)) = 0.1
        _ShadowStrength("阴影强度(基于遮罩)", Range(0, 1)) = 0.5 // 替换 _ShadowMultiplier
        _ShadowColor("阴影颜色", Color) = (0.5, 0.5, 0.7, 1) // 添加阴影颜色控制
        
        // AO 设置
        _AOMultiplier("AO强度", Range(0, 1)) = 0.5
        
        // 散射效果设置
        [Toggle(_SCATTERING)] _Scattering("启用散射效果", Float) = 1
        _ScatterColor("散射颜色", Color) = (1,0.8,0.6,1)
        _ScatterPower("散射范围", Range(1, 10)) = 3
        _ScatterThreshold("散射阈值", Range(0, 1)) = 0.2
        _ScatterSmooth("散射平滑度", Range(0.01, 1.0)) = 0.1
        _TranslucencyPower("透光强度", Range(1, 16)) = 8 // 新增参数
        
        // 阴影投射控制
        _ShadowDensity("阴影投射密度", Range(0, 1)) = 0.2 // 用于ShadowCaster Pass
        
        // 描边设置
        [Header(Outline Setting)]
        [Toggle(_USE_OUTLINE)] _UseOutline("启用描边", Float) = 1
        _OutlineColor("描边颜色", Color) = (0.1, 0.1, 0.1, 1)
        _OutlineWidth("描边宽度", Range(0, 10)) = 1.0
        [Toggle] _UseVertexColor("使用顶点色作为描边遮罩", Float) = 0
        _OutlineZOffset("描边深度偏移", Range(0, 1)) = 0.0001

        // 在Properties部分添加
        [Header(Eyebrow Penetration)]
        [Toggle(_USE_EYEBROW_MASK)] _UseEyebrowMask("启用眉毛穿透效果", Float) = 1
        _EyebrowMaskStrength("眉毛遮罩强度", Range(0, 1)) = 1.0
        _EyebrowTransparency("眉毛区域透明度", Range(0, 1)) = 0.3 // 默认值0.3, 可以调低让眉毛更清晰
        _EyebrowEdgeSmooth("眉毛边缘平滑", Range(0, 0.5)) = 0.05 // 小值使边缘更锐利
        _EyebrowMaskOffset("眉毛遮罩偏移(XY)", Vector) = (0,0,0,0)
        _EyebrowMaskTiling("眉毛遮罩缩放(XY)", Vector) = (1,1,0,0)
        [Toggle(_DEBUG_EYEBROW_MASK)] _DebugEyebrowMask("调试显示遮罩", Float) = 0


        // 基本渲染设置
        [HideInInspector] _Surface("__surface", Float) = 0.0
        [HideInInspector] _Blend("__blend", Float) = 0.0
        [HideInInspector] _AlphaClip("__clip", Float) = 0.0
        [HideInInspector] _SrcBlend("__src", Float) = 1.0
        [HideInInspector] _DstBlend("__dst", Float) = 0.0
        [HideInInspector] _ZWrite("__zw", Float) = 1.0
        [HideInInspector] _Cull("__cull", Float) = 2.0
        [HideInInspector] _ReceiveShadows("Receive Shadows", Float) = 1.0

        // --- Surface Options ---
        [Header(Surface Options)]
        [Enum(UnityEngine.Rendering.CullMode)] _Cull("Cull Mode", Float) = 2 // Back
        [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("Src Blend", Float) = 1 // One
        [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("Dst Blend", Float) = 0 // Zero
        [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("Blend Operation", Float) = 0 // Add
        [Toggle] _ZWrite("ZWrite", Float) = 1
        [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 // LEqual

        // --- Stencil Settings ---
        [Header(Stencil Settings)]
        _StencilRef("Stencil Ref", Float) = 0
        [Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comp", Float) = 8 // Always
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilPass("Stencil Pass", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilFail("Stencil Fail", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilZFail("Stencil ZFail", Float) = 0 // Keep
        [IntRange] _StencilReadMask("Read Mask", Range(0, 255)) = 255
        [IntRange] _StencilWriteMask("Write Mask", Range(0, 255)) = 255

        // --- Overlay Settings ---
        [Header(Overlay Settings)]
        [Toggle(_OVERLAY_ENABLED)] _DrawOverlay("Enable Overlay", Float) = 0 // 修正: 使用 _OVERLAY_ENABLED
        [Enum(UnityEngine.Rendering.BlendMode)] _OverlaySrcBlend("Overlay Src Blend", Float) = 5 // 修正: SrcAlpha (5)
        [Enum(UnityEngine.Rendering.StencilOp)] _OverlayStencilPass("Stencil Pass", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _OverlayStencilFail("Stencil Fail", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _OverlayStencilZFail("Stencil ZFail", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.BlendMode)] _OverlayDstBlend("Overlay Dst Blend", Float) = 10 // 修正: OneMinusSrcAlpha (10)
        [Enum(UnityEngine.Rendering.BlendOp)] _OverlayBlendOp("Overlay Blend Op", Float) = 0 // Add
        _OverlayStencilRef("Overlay Stencil Ref", Float) = 0
        [Enum(UnityEngine.Rendering.CompareFunction)] _OverlayStencilComp("Overlay Stencil Comp", Float) = 8 // Always

    }

    SubShader
    {
        Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "RenderPipeline" = "UniversalPipeline"}
        LOD 300


        // --- 主Pass ---
        Pass
        {
            Name "ForwardLit"
            Tags {"LightMode" = "UniversalForward"}
            
            // 确保设置了混合模式
            Blend SrcAlpha OneMinusSrcAlpha
            ZWrite On
            Cull Back

            Stencil
            {
                Ref [_StencilRef]
                Comp [_StencilComp]
                Pass [_StencilPass]
                Fail [_StencilFail]
                ZFail [_StencilZFail]
                ReadMask [_StencilReadMask]
                WriteMask [_StencilWriteMask]
            }

            HLSLPROGRAM
            #pragma vertex vert // 函数名来自 include 文件
            #pragma fragment frag // 函数名来自 include 文件
            #pragma prefer_hlslcc gles
            #pragma exclude_renderers d3d11_9x
            
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
            #pragma multi_compile _ _SHADOWS_SOFT
            #pragma multi_compile_fog
            #pragma shader_feature_local _SCATTERING // 散射特性
            // 在#pragma指令区域添加
            #pragma shader_feature_local _USE_EYEBROW_MASK
            #pragma shader_feature_local _DEBUG_EYEBROW_MASK

            // 包含共享的 HLSL 代码
            #include "ToonHairForwardPass.hlsl" 
            
            ENDHLSL
        }

        // --- 修改描边Pass ---
        Pass
        {
            Name "Outline"
            Tags { "LightMode" = "SRPDefaultUnlit" }
            Cull Front
            ZWrite On
            
            // 添加混合模式支持透明
            Blend SrcAlpha OneMinusSrcAlpha
            
            // 使用与主Pass相同的模板测试设置
            Stencil
            {
                Ref [_StencilRef]
                Comp [_StencilComp]
                Pass [_StencilPass]
                Fail [_StencilFail]
                ZFail [_StencilZFail]
                ReadMask [_StencilReadMask]
                WriteMask [_StencilWriteMask]
            }
            
            HLSLPROGRAM
            #pragma vertex OutlineVert
            #pragma fragment OutlineFrag
            #pragma multi_compile_fog
            #pragma shader_feature_local _ _USE_OUTLINE
            #pragma shader_feature_local _ _USE_VERTEXCOLOR
            #pragma shader_feature_local _USE_EYEBROW_MASK
            
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            
            CBUFFER_START(UnityPerMaterial)
            float4 _BaseMap_ST;
            float4 _OutlineColor;
            float _OutlineWidth;
            float _OutlineZOffset;
            
            // 眉毛遮罩相关参数
            float _UseEyebrowMask;
            float4 _EyebrowMaskOffset;
            float4 _EyebrowMaskTiling;
            float _EyebrowTransparency;
            float _EyebrowEdgeSmooth;
            float _EyebrowMaskStrength;
            // 其他必要的属性...
            CBUFFER_END
            
            // 眉毛遮罩贴图
            TEXTURE2D(_EyebrowMaskTexture); 
            SAMPLER(sampler_EyebrowMaskTexture);
            
            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                float2 texcoord : TEXCOORD0;
                #ifdef _USE_VERTEXCOLOR
                float4 color : COLOR;
                #endif
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };
            
            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float fogCoord : TEXCOORD1;
                // 新增屏幕位置用于采样RT
                float4 screenPos : TEXCOORD2;
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            Varyings OutlineVert(Attributes input)
            {
                Varyings output = (Varyings)0;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, output);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
                
                #if defined(_USE_OUTLINE)
                    // 确保描边宽度足够可见
                    float outlineScale = _OutlineWidth * 0.03;
                    
                    #if defined(_USE_VERTEXCOLOR)
                    outlineScale *= input.color.a;
                    #endif
                    
                    float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
                    float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
                    
                    // 在世界空间扩展
                    positionWS += normalWS * outlineScale;
                    
                    // 转换到裁剪空间
                    output.positionCS = TransformWorldToHClip(positionWS);
                    
                    // 应用Z偏移
                    output.positionCS.z -= _OutlineZOffset * 0.1;
                    
                    // 计算屏幕位置用于采样RT
                    output.screenPos = ComputeScreenPos(output.positionCS);
                #else
                    output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
                    output.screenPos = ComputeScreenPos(output.positionCS);
                #endif
                
                output.fogCoord = ComputeFogFactor(output.positionCS.z);
                return output;
            }
            
            half4 OutlineFrag(Varyings input) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
                
                half4 color = _OutlineColor;
                
                // 采样眉毛遮罩并应用透明度
                #if defined(_USE_EYEBROW_MASK)
                    // 计算屏幕UV
                    float2 screenUV = input.screenPos.xy / input.screenPos.w;
                    
                    // 应用缩放和偏移
                    screenUV = screenUV * _EyebrowMaskTiling.xy + _EyebrowMaskOffset.xy;
                    
                    // 采样眉毛遮罩
                    float eyebrowMask = SAMPLE_TEXTURE2D(_EyebrowMaskTexture, sampler_EyebrowMaskTexture, screenUV).r;
                    
                    // 平滑处理遮罩边缘
                    eyebrowMask = smoothstep(_EyebrowEdgeSmooth, 1.0 - _EyebrowEdgeSmooth, eyebrowMask);
                    
                    // 根据眉毛遮罩调整透明度
                    // 在眉毛区域降低描边的透明度
                    if (eyebrowMask > 0.01)
                    {
                        color.a *= (1.0 - eyebrowMask * _EyebrowMaskStrength);
                    }
                #endif
                
                color.rgb = MixFog(color.rgb, input.fogCoord);
                return color;
            }
            ENDHLSL
        }

        // 阴影投射Pass（修复版）
        Pass
        {
            Name "ShadowCaster"
            Tags {"LightMode" = "ShadowCaster"}
            
            ZWrite On
            ZTest LEqual
            ColorMask 0
            Cull [_Cull]

            Stencil
            {
                Ref [_StencilRef]
                Comp [_StencilComp]
                Pass [_StencilPass]
                Fail [_StencilFail]
                ZFail [_StencilZFail]
                ReadMask [_StencilReadMask]
                WriteMask [_StencilWriteMask]
            }

            HLSLPROGRAM
            #pragma vertex ShadowPassVertex
            #pragma fragment ShadowPassFragment
            
            // 添加目标平台指令
            #pragma target 2.0
            
            // 这里只包含基础必需的库
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
            
            float4 _BaseMap_ST;
            float _ShadowDensity;
            
            struct Attributes
            {
                float4 positionOS   : POSITION;
                float3 normalOS     : NORMAL;
                float2 texcoord     : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };
            
            struct Varyings
            {
                float2 uv           : TEXCOORD0;
                float4 positionCS   : SV_POSITION;
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            float3 _LightDirection;
            
            float4 GetShadowPositionHClip(Attributes input)
            {
                float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
                float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
                
                // 使用主光源方向，如果没有指定的话
                float3 lightDirection = _LightDirection;
                float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirection));
                
                #if UNITY_REVERSED_Z
                positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
                #else
                positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
                #endif
                
                return positionCS;
            }
            
            Varyings ShadowPassVertex(Attributes input)
            {
                Varyings output;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, output);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
                
                output.uv = TRANSFORM_TEX(input.texcoord, _BaseMap);
                output.positionCS = GetShadowPositionHClip(input);
                return output;
            }
            
            half4 ShadowPassFragment(Varyings input) : SV_TARGET
            {
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
                return half4(_ShadowDensity, _ShadowDensity, _ShadowDensity, 1.0);
            }
            
            ENDHLSL
        }



        
    }
    
    FallBack "Universal Render Pipeline/Lit"
    CustomEditor "UnityEditor.ShaderGraph.PBRMasterGUI"
}